package way.scripts.util;

import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
import way.scripts.classDoc.model.LevelEnum;
import way.scripts.classDoc.model.Table;

import java.io.*;
import java.util.List;

/**
 * @author Haozhiqiang  {2021/12/7 16:22}
 */
public class XWPFDocumentBuilder implements Closeable {

    private XWPFDocument document;

    private final String outFile;

    public XWPFDocumentBuilder(String templateFile, String outFile) throws IOException, XmlException {
        this.outFile = outFile;
        init(templateFile);
    }

    private void init(String templateFile) throws IOException, XmlException {
        CTStyles ctStyles;
        try (XWPFDocument model = new XWPFDocument(new FileInputStream(new File(templateFile)))) {
            ctStyles = model.getStyle();
        }

        this.document = new XWPFDocument();
        XWPFStyles docStyle = this.document.createStyles();
        docStyle.setStyles(ctStyles);
    }

    @Override
    public void close() throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(outFile)) {
            this.document.write(outputStream);
        } finally {
            this.document.close();
        }
    }

    public void addBreak() {
        this.document.createParagraph().createRun().addBreak();
    }

    public void addTitle(String title, LevelEnum levelEnum) {
        XWPFParagraph paragraph = this.document.createParagraph();
        paragraph.setStyle(levelEnum.getStyleId());
        XWPFRun run = paragraph.createRun();
        run.setText(title);
    }

    public void addTable(Table table) {
        String[] columns = table.getColumns();

        XWPFTable docTable = this.document.createTable();
        docTable.setStyleID("16");

        XWPFTableRow tableRowOne = docTable.getRow(0);
        tableRowOne.getCell(0).setText(table.getColumns()[0]);
        for (int i = 1; i < columns.length; i ++) {
            tableRowOne.addNewTableCell().setText(columns[i]);
        }

        List<List<String>> rows = table.getRows();
        rows.forEach(row -> {
            XWPFTableRow tableRow = docTable.createRow();
            for (int i = 0; i < columns.length; i++) {
                tableRow.getCell(i).setText(row.get(i));
            }
        });
    }
}
